<template>
  <Teleport to="body">
    <!--右键点击菜单-->
    <div class="context-menu" ref="listBox" :style="{
      'left': left + 'px',
      'top': top + 'px',
      'height': heightV + 'px'
    }">
      <div class="list-body" ref="listBody" :style="{
        opacity: heightV > 0?'100%':'0'
      }">
        <!--放 items-->
        <slot></slot>
      </div>

    </div>
  </Teleport>

</template>
<script setup>
import { ref, watch, onMounted } from "vue"
const props = defineProps({
  //控制显示和隐藏
  isShow: {
    type: Boolean,
    default: false,
  },
  left: {
    type: Number,
    default: 0
  },
  top: {
    type: Number,
    default: 0
  }
})

//获得子元素的高度
const listBody = ref(null)

const listBox = ref(null)

const heightV = ref(0)

const emit = defineEmits(['update:top', 'update:left'])

const handleShow = () => {
  const sonDom = listBody.value

  let height = sonDom.clientHeight
  let width = sonDom.clientWidth
  if (props.isShow) {
    //开启的时候还要注意是否扎出界面外了
    heightV.value = height

    //计算是否达到了高度的边界
    let bottomLength = document.body.clientHeight - props.top - height

    //计算是否到达了最右侧
    let sideLength = document.body.clientWidth - props.left - width

    if (bottomLength <= 0) {
      //如果到达高度边界了 那就top升高
      emit('update:top', props.top - height)
      //v-model:top=""
    }

    if (sideLength <= 0) {
      //如果到达高度边界了 那就top升高
      emit('update:left', props.left - width)
    }


  } else {
    heightV.value = 0
  }
}


onMounted(() => {
  handleShow()
})

watch([() => props.isShow,()=>props.top,()=>props.left], ([new1,new2,new3])=> {
  handleShow();
});

</script>
<style lang="scss">
.context-menu {
  position: fixed;
  width: 160px;
  top: 0;
  left: 0;
  z-index: 500;
  font-size: 14px;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 2px 15px -5px rgba(0, 0, 0, .4);
  transition: height .15s;
}
</style>